package com.apes.fico.masterdata.gl.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.DateUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author Chengxm
 * @desc 会计期间档案
 * @create 2018年12月20日15:16:31
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = AccountingPeriod.CONST_TABLE_NAME, indexes = {
        @Index(columnList = "year,company_id", unique = true)
})
public class AccountingPeriod extends Model {
    public final static String CONST_TABLE_NAME = "mas_acc_period";

    @Id
    @Column(name = "id", length = 8)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "会计期间")
    @Comment("编号")
    private String id;

    @Column(name = "year", nullable = false)
    private int year;//会计年度

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company;

    @NotNull
    @Column
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    private Date fromDate;

    @NotNull
    @Column
    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    private Date thruDate;

    @OneToMany(mappedBy = "accountingPeriod", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("period_num asc")
    private List<AccountingPeriodItem> accountingPeriodItems = new ArrayList<>();

    public List<AccountingPeriodItem> getAccountingPeriodItems() {
        if (accountingPeriodItems == null||accountingPeriodItems.isEmpty()) return new ArrayList<>();
        for (AccountingPeriodItem item : accountingPeriodItems) {
            item.setAccountingPeriod(this);
        }
        return accountingPeriodItems;
    }

    @OneToMany(mappedBy = "accountingPeriods", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<AccountingPeriodQuartItem> accountingPeriodQuartItems = new ArrayList<>();

    public List<AccountingPeriodQuartItem> getAccountingPeriodQuartItems() {
        if (accountingPeriodQuartItems == null||accountingPeriodQuartItems.isEmpty()) return new ArrayList<>();
        for (AccountingPeriodQuartItem item : accountingPeriodQuartItems) {
            item.setAccountingPeriods(this);
        }
        return accountingPeriodQuartItems;
    }


}
